package servletPackage;

import inspur.dao.BookDao;
import inspur.dao.CookieDao;
import inspur.dao.UserDao;
import inspur.entity.BookObject;
import inspur.entity.CookieTokenObject;
import inspur.entity.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;

@WebServlet(name = " BorrowBookServlet")
public class BorrowBookServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setCharacterEncoding("utf-8");
        PrintWriter out=response.getWriter();
        String bookId=request.getParameter("bookId");
        if (bookId==null){
            out.print("提醒，需要填写一个书籍编号");
            return;
        }else{
            if (bookId.equals("")){
                out.print("提醒，需要填写一个书籍编号");
                return;
            }
        }
        //

        String CookieUserId= CookieDao.getCookieItemValue(request,"userid");
        if (CookieUserId==null){
            out.print("借书失败，原因：你没有登录");
        }else{

            User SQLmyUser= UserDao.getUserByUserId(CookieUserId);
            CookieTokenObject cto= CookieDao.CreatCookieTokenObject(request);
            boolean ctoIsOk=CookieDao.isTrueToken(cto,SQLmyUser.getPassword(),request);
            if (ctoIsOk&&SQLmyUser.getIdentity().equals("user")||SQLmyUser.getIdentity().equals("admin")){
                BookObject status=BookDao.SelectBookById(bookId);

                if (status.getStatus().equals("0")){
                    out.print("借书失败，原因：该图书已经被借走");
                }else {
                    status.setUserid(CookieUserId);
                    status.setStatus("0");
                    long now=new Date().getTime()/1000;
                    status.setStartDate(now+"");
                    status.setUserTime("7day");
                    long time=24*60*60*7;
                    status.setReturnBoookTime(now+time+"");
                    int flag= BookDao.UpdateBook(bookId,status);
                    System.out.println(flag);
                    if (flag==2){
                        out.print("success");
                        System.out.print("借书success");
                    }else if(flag==3) {
                        out.print("借书失败，原因：没有该图书");
                        System.out.print("3");
                    }else{
                        out.print("数据库出现未知错误，请联系管理员");

                    }
                }
            }else {
                out.print("你没有权限处理这个请求，你必须是标准用户或管理员才能借书,也可能是你的cookie损坏，请重置浏览器后重试");
            }
        }


        out.close();
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }
}
